import React, { useState } from 'react';
import { Upload, message } from 'antd';
import type { GetProp, UploadProps } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { uploadFile } from '@/services/api';
import styles from './index.less';

const { Dragger } = Upload;

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

const beforeUpload = (file: FileType) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('Image must smaller than 10MB!');
  }
  return isJpgOrPng && isLt10M;
};

interface UploadComponentProps {
  imageUrl: string | undefined;
  setImageUrl: React.Dispatch<React.SetStateAction<string | undefined>>;
}


const UploadComponent: React.FC<UploadComponentProps> = ({ imageUrl, setImageUrl }) => {

  const handleChange: UploadProps['onChange'] = async (info) => {
    if (info.file.status === 'uploading') {
      return;
    }
    console.log('info:', info);

    console.log('imageUrl:', imageUrl);
    if (info.file.status === 'done') {
      const file = info.file.originFileObj as File;
      console.log('file_name:', file.name);
      const uploadUrl = info.file.response.data
      setImageUrl(uploadUrl);
      console.log('上传图片url:', uploadUrl);
    }
  };

  const baseUrl = process.env.BASE_URL === '/' ? window.location.host : process.env.BASE_URL;
  console.log('BASE_URL:',  process.env.BASE_URL)
  console.log('window.location.host:',  window.location.host)
  console.log('baseUrl:', baseUrl)

  const uploadProps: UploadProps = {
    name: 'file',
    accept: '.jpg,.jpeg,.png',
    maxCount: 1,
    multiple: false,
    action: '/file/upload',
    onChange: handleChange,
    beforeUpload: beforeUpload,
    showUploadList: false,
    progress: {
      strokeWidth: 4,
      format: (percent) => percent && `${parseFloat(percent.toFixed(2))}%`,
      strokeColor: {
        '0%': '#108ee9',
        '100%': '#87d068',
      },
    }
  };

  return (
    <Dragger
      {...uploadProps}
      className={styles.customDragger}
    >
      <div className={styles.uploadContent}>
        {imageUrl ? (
          <img
            src={imageUrl}
            alt="uploaded"
            style={{
              maxHeight: '80px',
              width: 'auto',
              objectFit: 'contain'
            }}
          />
        ) : (
          <div className={styles.uploadPlaceholder}>
            <UploadOutlined />
            <p>点击上传</p>
          </div>
        )}
      </div>
    </Dragger>
  )
}

export default UploadComponent;